#####################################################################
###### REPLICATION CODE FOR "CONVERGENT FLEXIBILITY: HOW ############
###### INTERNATIONAL LAW KEEPS PACE WITH TECHNOLOGICAL CHANGE #######
#####################################################################

## This file can be used to explore or reuse the data.

rm(list=ls()) # Clear environment (optional)
graphics.off()
library(plyr)
library(dplyr)
library(tidyr)
library(broom)
library(ggplot2)
set.seed(888)  
options("scipen"=100, "digits"=4) 



######## PREPARING DATA #########

setwd("/Users/user/file location") # change as needed


## Load file from registration survey (pretreatment)
pre <- read.csv("cf_registration.csv") 

## Load file for experiment 
post <- read.csv("cf_experiment.csv") 
intersect(names(pre), names(post))


## Covariates preceded by "X_"; separate and alphabetize
x_cols <- grep("^X_", names(pre), value = TRUE)
non_x_cols <- setdiff(names(pre), x_cols)
x_sorted <- sort(x_cols)
new_order <- c(non_x_cols, x_sorted)
pre <- pre[, new_order, drop = FALSE]
pre$X_LocationISO <- NULL


## Treat "" as NA across both files
pre <- pre %>%
  mutate(across(where(is.factor), as.character)) %>%                 # factors -> character
  mutate(across(where(is.character), ~ na_if(trimws(.x), ""))) %>%   # "" -> NA in character cols
  mutate(across(where(is.character), ~ na_if(.x, "NA")))             # optional: literal "NA" -> NA

post <- post %>%
  mutate(across(where(is.factor), as.character)) %>%                 # factors -> character
  mutate(across(where(is.character), ~ na_if(trimws(.x), ""))) %>%   # "" -> NA in character cols
  mutate(across(where(is.character), ~ na_if(.x, "NA")))             # optional: literal "NA" -> NA


## Merge into a single dataframe for easy analysis
df <- merge(pre, post, by=c("Synthetic_ID", "LawSocID"), all=T)


## Scale aversion scores (only available for later waves)
df$X_Aversion_Risk <- scale(df$X_Aversion_Risk, center = TRUE)
df$X_Aversion_Ambiguity <- scale(df$X_Aversion_Ambiguity, center = TRUE)


####### PREVIEW IMPORTED DATA ########

## Added from Nyrup et al (BJPS, 2025): Proportion of cabinet officials since 1960 with terminal law degrees
hist(df$X_LawPtP)

## Added from Polity V: Regime type score
hist(df$X_Polity)

## Added from Guerriero (Data in Brief, 2016): Legal tradition type
hist(df$X_ShariaLaw)
hist(df$X_CommonLaw)
hist(df$X_PureCivil)

## For variable coding rules, see Appendix A.5.








